<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import { Upload, Picture, Document, Camera, View } from '@element-plus/icons-vue'
import request from '@/utils/request'

const router = useRouter()

// 响应式数据
const activeTab = ref('image')
const loading = ref(false)
const uploadLoading = ref(false)

// 图片识别相关
const imageForm = reactive({
  image: null,
  recognition_type: 'symptom'
})

const recognitionTypes = [
  { label: '症状识别', value: 'symptom' },
  { label: '皮肤病识别', value: 'skin' },
  { label: '口腔识别', value: 'oral' },
  { label: '眼部识别', value: 'eye' }
]

// OCR识别相关
const ocrForm = reactive({
  document: null,
  document_type: 'blood_test'
})

const documentTypes = [
  { label: '血常规报告', value: 'blood_test' },
  { label: 'CT报告', value: 'ct_report' },
  { label: 'MRI报告', value: 'mri_report' },
  { label: '超声报告', value: 'ultrasound' },
  { label: 'X光片', value: 'xray' },
  { label: '处方单', value: 'prescription' },
  { label: '病历', value: 'medical_record' },
  { label: '其他', value: 'other' }
]

// 多模态问诊相关
const consultationForm = reactive({
  symptom_description: '',
  duration: '',
  severity: 5,
  image: null,
  document: null,
  recognition_type: 'symptom',
  document_type: 'blood_test'
})

// 结果数据
const recognitionResult = ref(null)
const ocrResult = ref(null)
const consultationResult = ref(null)

// 历史记录
const recognitionHistory = ref([])
const ocrHistory = ref([])
const consultationHistory = ref([])

// 图片上传前验证
const beforeImageUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!')
    return false
  }
  
  imageForm.image = file
  return false // 阻止自动上传
}

// 文档上传前验证
const beforeDocumentUpload = (file) => {
  const isValidType = ['image/jpeg', 'image/jpg', 'image/png', 'application/pdf'].includes(file.type)
  const isLt10M = file.size / 1024 / 1024 < 10

  if (!isValidType) {
    ElMessage.error('只能上传JPG、PNG或PDF文件!')
    return false
  }
  if (!isLt10M) {
    ElMessage.error('文档大小不能超过 10MB!')
    return false
  }
  
  ocrForm.document = file
  return false // 阻止自动上传
}

// 多模态问诊图片上传
const beforeConsultationImageUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!')
    return false
  }
  
  consultationForm.image = file
  return false
}

// 多模态问诊文档上传
const beforeConsultationDocumentUpload = (file) => {
  const isValidType = ['image/jpeg', 'image/jpg', 'image/png', 'application/pdf'].includes(file.type)
  const isLt10M = file.size / 1024 / 1024 < 10

  if (!isValidType) {
    ElMessage.error('只能上传JPG、PNG或PDF文件!')
    return false
  }
  if (!isLt10M) {
    ElMessage.error('文档大小不能超过 10MB!')
    return false
  }
  
  consultationForm.document = file
  return false
}

// 图片识别
const handleImageRecognition = async () => {
  if (!imageForm.image) {
    ElMessage.warning('请先上传图片')
    return
  }

  const formData = new FormData()
  formData.append('image', imageForm.image)
  formData.append('recognition_type', imageForm.recognition_type)

  uploadLoading.value = true
  try {
    const response = await request.post('/recognition/image-recognition/', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })

    if (response.data.code === 0) {
      recognitionResult.value = response.data.data
      ElMessage.success('图片识别完成')
      await loadRecognitionHistory()
    } else {
      ElMessage.error(response.data.msg || '识别失败')
    }
  } catch (error) {
    console.error('图片识别失败:', error)
    ElMessage.error('识别失败，请重试')
  } finally {
    uploadLoading.value = false
  }
}

// 文档OCR识别
const handleDocumentOCR = async () => {
  if (!ocrForm.document) {
    ElMessage.warning('请先上传文档')
    return
  }

  const formData = new FormData()
  formData.append('document', ocrForm.document)
  formData.append('document_type', ocrForm.document_type)

  uploadLoading.value = true
  try {
    const response = await request.post('/recognition/document-ocr/', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })

    if (response.data.code === 0) {
      ocrResult.value = response.data.data
      ElMessage.success('文档OCR识别完成')
      await loadOCRHistory()
    } else {
      ElMessage.error(response.data.msg || 'OCR识别失败')
    }
  } catch (error) {
    console.error('文档OCR失败:', error)
    ElMessage.error('OCR识别失败，请重试')
  } finally {
    uploadLoading.value = false
  }
}

// 多模态问诊
const handleMultiModalConsultation = async () => {
  if (!consultationForm.symptom_description && !consultationForm.image && !consultationForm.document) {
    ElMessage.warning('请至少提供症状描述、图片或文档中的一项')
    return
  }

  const formData = new FormData()
  formData.append('symptom_description', consultationForm.symptom_description)
  formData.append('duration', consultationForm.duration)
  formData.append('severity', consultationForm.severity)
  
  if (consultationForm.image) {
    formData.append('image', consultationForm.image)
    formData.append('recognition_type', consultationForm.recognition_type)
  }
  
  if (consultationForm.document) {
    formData.append('document', consultationForm.document)
    formData.append('document_type', consultationForm.document_type)
  }

  uploadLoading.value = true
  try {
    const response = await request.post('/recognition/multi-modal-consultation/', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })

    if (response.data.code === 0) {
      consultationResult.value = response.data.data
      ElMessage.success('多模态问诊创建成功')
      await loadConsultationHistory()
    } else {
      ElMessage.error(response.data.msg || '问诊创建失败')
    }
  } catch (error) {
    console.error('多模态问诊失败:', error)
    ElMessage.error('问诊创建失败，请重试')
  } finally {
    uploadLoading.value = false
  }
}

// 加载历史记录
const loadRecognitionHistory = async () => {
  try {
    const response = await request.get('/recognition/image-recognition/')
    if (response.data.code === 0) {
      recognitionHistory.value = response.data.data.list
    }
  } catch (error) {
    console.error('加载识别历史失败:', error)
  }
}

const loadOCRHistory = async () => {
  try {
    const response = await request.get('/recognition/document-ocr/')
    if (response.data.code === 0) {
      ocrHistory.value = response.data.data.list
    }
  } catch (error) {
    console.error('加载OCR历史失败:', error)
  }
}

const loadConsultationHistory = async () => {
  try {
    const response = await request.get('/recognition/multi-modal-consultation/')
    if (response.data.code === 0) {
      consultationHistory.value = response.data.data.list
    }
  } catch (error) {
    console.error('加载问诊历史失败:', error)
  }
}

// 查看详情
const viewRecognitionDetail = async (id) => {
  try {
    const response = await request.get(`/recognition/recognition/${id}/`)
    if (response.data.code === 0) {
      recognitionResult.value = response.data.data
      activeTab.value = 'image'
    }
  } catch (error) {
    ElMessage.error('获取详情失败')
  }
}

const viewOCRDetail = async (id) => {
  try {
    const response = await request.get(`/recognition/ocr/${id}/`)
    if (response.data.code === 0) {
      ocrResult.value = response.data.data
      activeTab.value = 'ocr'
    }
  } catch (error) {
    ElMessage.error('获取详情失败')
  }
}

// 重置表单
const resetImageForm = () => {
  imageForm.image = null
  recognitionResult.value = null
}

const resetOCRForm = () => {
  ocrForm.document = null
  ocrResult.value = null
}

const resetConsultationForm = () => {
  consultationForm.symptom_description = ''
  consultationForm.duration = ''
  consultationForm.severity = 5
  consultationForm.image = null
  consultationForm.document = null
  consultationResult.value = null
}

// 格式化时间
const formatTime = (timeStr) => {
  return new Date(timeStr).toLocaleString()
}

// 获取状态标签类型
const getStatusType = (status) => {
  const statusMap = {
    'pending': 'info',
    'processing': 'warning',
    'completed': 'success',
    'failed': 'danger'
  }
  return statusMap[status] || 'info'
}

onMounted(() => {
  loadRecognitionHistory()
  loadOCRHistory()
  loadConsultationHistory()
})
</script>

<template>
  <div class="image-recognition-page">
    <div class="page-header">
      <h2>多模态问诊辅助诊断</h2>
      <p>结合百度AI图像识别与OCR技术，为在线问诊提供多维度辅助决策支持</p>
    </div>

    <el-tabs v-model="activeTab" class="main-tabs">
      <!-- 图片识别 -->
      <el-tab-pane label="症状图片识别" name="image">
        <div class="tab-content">
          <el-card class="upload-card">
            <template #header>
              <div class="card-header">
                <span>上传症状图片</span>
                <el-button type="text" @click="resetImageForm">重置</el-button>
              </div>
            </template>
            
            <div class="upload-section">
              <el-upload
                class="upload-dragger"
                drag
                :before-upload="beforeImageUpload"
                accept="image/*"
                :show-file-list="false"
              >
                <el-icon class="el-icon--upload"><upload /></el-icon>
                <div class="el-upload__text">
                  将图片拖到此处，或<em>点击上传</em>
                </div>
                <template #tip>
                  <div class="el-upload__tip">
                    支持JPG/PNG格式，文件大小不超过5MB
                  </div>
                </template>
              </el-upload>
              
              <div v-if="imageForm.image" class="uploaded-file">
                <el-icon><picture /></el-icon>
                <span>{{ imageForm.image.name }}</span>
                <el-button type="text" size="small" @click="imageForm.image = null">移除</el-button>
              </div>
            </div>
            
            <div class="form-section">
              <el-form-item label="识别类型">
                <el-select v-model="imageForm.recognition_type" placeholder="请选择识别类型">
                  <el-option
                    v-for="type in recognitionTypes"
                    :key="type.value"
                    :label="type.label"
                    :value="type.value"
                  />
                </el-select>
              </el-form-item>
              
              <el-button
                type="primary"
                :loading="uploadLoading"
                @click="handleImageRecognition"
                :disabled="!imageForm.image"
              >
                开始识别
              </el-button>
            </div>
          </el-card>

          <!-- 识别结果 -->
          <el-card v-if="recognitionResult" class="result-card">
            <template #header>
              <div class="card-header">
                <span>识别结果</span>
                <el-tag :type="getStatusType(recognitionResult.status)">
                  {{ recognitionResult.status === 'completed' ? '识别完成' : '识别中' }}
                </el-tag>
              </div>
            </template>
            
            <div v-if="recognitionResult.status === 'completed'">
              <div class="result-section">
                <h4>建议科室：{{ recognitionResult.suggested_department }}</h4>
                <div class="medical-advice">
                  <h5>医疗建议：</h5>
                  <p>{{ recognitionResult.medical_advice }}</p>
                </div>
              </div>
            </div>
          </el-card>
        </div>
      </el-tab-pane>

      <!-- 文档OCR -->
      <el-tab-pane label="报告OCR解析" name="ocr">
        <div class="tab-content">
          <el-card class="upload-card">
            <template #header>
              <div class="card-header">
                <span>上传医疗报告</span>
                <el-button type="text" @click="resetOCRForm">重置</el-button>
              </div>
            </template>
            
            <div class="upload-section">
              <el-upload
                class="upload-dragger"
                drag
                :before-upload="beforeDocumentUpload"
                accept="image/*,.pdf"
                :show-file-list="false"
              >
                <el-icon class="el-icon--upload"><upload /></el-icon>
                <div class="el-upload__text">
                  将文档拖到此处，或<em>点击上传</em>
                </div>
                <template #tip>
                  <div class="el-upload__tip">
                    支持JPG/PNG/PDF格式，文件大小不超过10MB
                  </div>
                </template>
              </el-upload>
              
              <div v-if="ocrForm.document" class="uploaded-file">
                <el-icon><document /></el-icon>
                <span>{{ ocrForm.document.name }}</span>
                <el-button type="text" size="small" @click="ocrForm.document = null">移除</el-button>
              </div>
            </div>
            
            <div class="form-section">
              <el-form-item label="文档类型">
                <el-select v-model="ocrForm.document_type" placeholder="请选择文档类型">
                  <el-option
                    v-for="type in documentTypes"
                    :key="type.value"
                    :label="type.label"
                    :value="type.value"
                  />
                </el-select>
              </el-form-item>
              
              <el-button
                type="primary"
                :loading="uploadLoading"
                @click="handleDocumentOCR"
                :disabled="!ocrForm.document"
              >
                开始OCR识别
              </el-button>
            </div>
          </el-card>

          <!-- OCR结果 -->
          <el-card v-if="ocrResult" class="result-card">
            <template #header>
              <div class="card-header">
                <span>OCR识别结果</span>
                <el-tag :type="getStatusType(ocrResult.status)">
                  {{ ocrResult.status === 'completed' ? '识别完成' : '识别中' }}
                </el-tag>
              </div>
            </template>
            
            <div v-if="ocrResult.status === 'completed'">
              <div class="result-section">
                <div class="extracted-text">
                  <h5>提取文本：</h5>
                  <p>{{ ocrResult.extracted_text }}</p>
                </div>
                
                <div v-if="ocrResult.medical_indicators" class="medical-indicators">
                  <h5>医疗指标：</h5>
                  <div class="indicators-list">
                    <div
                      v-for="indicator in ocrResult.medical_indicators"
                      :key="indicator.name"
                      class="indicator-item"
                    >
                      <span class="indicator-name">{{ indicator.name }}</span>
                      <span class="indicator-value">{{ indicator.value }} {{ indicator.unit }}</span>
                      <el-tag
                        :type="indicator.is_normal ? 'success' : 'warning'"
                        size="small"
                      >
                        {{ indicator.is_normal ? '正常' : '异常' }}
                      </el-tag>
                    </div>
                  </div>
                </div>
                
                <div class="interpretation">
                  <h5>解读结果：</h5>
                  <p>{{ ocrResult.interpretation }}</p>
                </div>
              </div>
            </div>
          </el-card>
        </div>
      </el-tab-pane>

      <!-- 多模态问诊 -->
      <el-tab-pane label="多模态问诊" name="consultation">
        <div class="tab-content">
          <el-card class="consultation-card">
            <template #header>
              <div class="card-header">
                <span>创建多模态问诊</span>
                <el-button type="text" @click="resetConsultationForm">重置</el-button>
              </div>
            </template>
            
            <el-form :model="consultationForm" label-width="120px">
              <el-form-item label="症状描述">
                <el-input
                  v-model="consultationForm.symptom_description"
                  type="textarea"
                  :rows="4"
                  placeholder="请详细描述您的症状..."
                />
              </el-form-item>
              
              <el-form-item label="持续时间">
                <el-input
                  v-model="consultationForm.duration"
                  placeholder="如：3天、1周、2个月等"
                />
              </el-form-item>
              
              <el-form-item label="严重程度">
                <el-slider
                  v-model="consultationForm.severity"
                  :min="1"
                  :max="10"
                  show-stops
                  :marks="{
                    1: '轻微',
                    5: '中等',
                    10: '严重'
                  }"
                />
              </el-form-item>
              
              <el-form-item label="症状图片">
                <el-upload
                  class="upload-dragger"
                  drag
                  :before-upload="beforeConsultationImageUpload"
                  accept="image/*"
                  :show-file-list="false"
                >
                  <el-icon class="el-icon--upload"><camera /></el-icon>
                  <div class="el-upload__text">
                    上传症状图片（可选）
                  </div>
                </el-upload>
                
                <div v-if="consultationForm.image" class="uploaded-file">
                  <el-icon><picture /></el-icon>
                  <span>{{ consultationForm.image.name }}</span>
                  <el-button type="text" size="small" @click="consultationForm.image = null">移除</el-button>
                </div>
              </el-form-item>
              
              <el-form-item label="检查报告">
                <el-upload
                  class="upload-dragger"
                  drag
                  :before-upload="beforeConsultationDocumentUpload"
                  accept="image/*,.pdf"
                  :show-file-list="false"
                >
                  <el-icon class="el-icon--upload"><document /></el-icon>
                  <div class="el-upload__text">
                    上传检查报告（可选）
                  </div>
                </el-upload>
                
                <div v-if="consultationForm.document" class="uploaded-file">
                  <el-icon><document /></el-icon>
                  <span>{{ consultationForm.document.name }}</span>
                  <el-button type="text" size="small" @click="consultationForm.document = null">移除</el-button>
                </div>
              </el-form-item>
              
              <el-form-item>
                <el-button
                  type="primary"
                  size="large"
                  :loading="uploadLoading"
                  @click="handleMultiModalConsultation"
                >
                  提交多模态问诊
                </el-button>
              </el-form-item>
            </el-form>
          </el-card>

          <!-- 问诊结果 -->
          <el-card v-if="consultationResult" class="result-card">
            <template #header>
              <div class="card-header">
                <span>问诊结果</span>
                <el-tag type="success">{{ consultationResult.consultation_id }}</el-tag>
              </div>
            </template>
            
            <div class="result-section">
              <div class="consultation-info">
                <h4>建议科室：{{ consultationResult.suggested_department }}</h4>
                <h4>紧急程度：{{ consultationResult.urgency_level }}</h4>
              </div>
              
              <div class="analysis-result">
                <h5>AI分析结果：</h5>
                <pre>{{ JSON.stringify(consultationResult.analysis_result, null, 2) }}</pre>
              </div>
            </div>
          </el-card>
        </div>
      </el-tab-pane>

      <!-- 历史记录 -->
      <el-tab-pane label="历史记录" name="history">
        <div class="tab-content">
          <el-tabs type="card">
            <el-tab-pane label="图片识别记录">
              <el-table :data="recognitionHistory" style="width: 100%">
                <el-table-column prop="recognition_type_display" label="识别类型" width="120" />
                <el-table-column prop="suggested_department" label="建议科室" width="120" />
                <el-table-column prop="status_display" label="状态" width="100">
                  <template #default="scope">
                    <el-tag :type="getStatusType(scope.row.status)">
                      {{ scope.row.status_display }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="created_at" label="创建时间" width="180">
                  <template #default="scope">
                    {{ formatTime(scope.row.created_at) }}
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="100">
                  <template #default="scope">
                    <el-button type="text" size="small" @click="viewRecognitionDetail(scope.row.id)">
                      查看
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
            
            <el-tab-pane label="OCR识别记录">
              <el-table :data="ocrHistory" style="width: 100%">
                <el-table-column prop="document_type_display" label="文档类型" width="120" />
                <el-table-column prop="status_display" label="状态" width="100">
                  <template #default="scope">
                    <el-tag :type="getStatusType(scope.row.status)">
                      {{ scope.row.status_display }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="created_at" label="创建时间" width="180">
                  <template #default="scope">
                    {{ formatTime(scope.row.created_at) }}
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="100">
                  <template #default="scope">
                    <el-button type="text" size="small" @click="viewOCRDetail(scope.row.id)">
                      查看
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
            
            <el-tab-pane label="问诊记录">
              <el-table :data="consultationHistory" style="width: 100%">
                <el-table-column prop="consultation_id" label="问诊ID" width="150" />
                <el-table-column prop="symptom_description" label="症状描述" show-overflow-tooltip />
                <el-table-column prop="suggested_department" label="建议科室" width="120" />
                <el-table-column prop="urgency_level" label="紧急程度" width="100" />
                <el-table-column prop="status_display" label="状态" width="100">
                  <template #default="scope">
                    <el-tag type="success">{{ scope.row.status_display }}</el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="created_at" label="创建时间" width="180">
                  <template #default="scope">
                    {{ formatTime(scope.row.created_at) }}
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
          </el-tabs>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<style scoped>
.image-recognition-page {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.page-header {
  text-align: center;
  margin-bottom: 30px;
}

.page-header h2 {
  color: #333;
  margin-bottom: 10px;
}

.page-header p {
  color: #666;
  font-size: 14px;
}

.main-tabs {
  margin-top: 20px;
}

.tab-content {
  padding: 20px 0;
}

.upload-card,
.consultation-card,
.result-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.upload-section {
  margin-bottom: 20px;
}

.upload-dragger {
  width: 100%;
}

.uploaded-file {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px;
  background: #f5f7fa;
  border-radius: 4px;
  margin-top: 10px;
}

.form-section {
  display: flex;
  align-items: center;
  gap: 20px;
}

.result-section {
  padding: 20px 0;
}

.result-section h4,
.result-section h5 {
  margin-bottom: 10px;
  color: #333;
}

.medical-advice,
.extracted-text,
.interpretation {
  margin-bottom: 20px;
}

.medical-indicators {
  margin-bottom: 20px;
}

.indicators-list {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 10px;
}

.indicator-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px;
  background: #f9f9f9;
  border-radius: 4px;
}

.indicator-name {
  font-weight: bold;
  min-width: 100px;
}

.indicator-value {
  flex: 1;
}

.consultation-info {
  margin-bottom: 20px;
}

.consultation-info h4 {
  margin-bottom: 10px;
}

.analysis-result {
  background: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  margin-top: 20px;
}

.analysis-result pre {
  white-space: pre-wrap;
  word-break: break-word;
  font-size: 12px;
  line-height: 1.4;
}

@media (max-width: 768px) {
  .image-recognition-page {
    padding: 10px;
  }
  
  .form-section {
    flex-direction: column;
    align-items: stretch;
  }
  
  .indicators-list {
    grid-template-columns: 1fr;
  }
}
</style>
